package com.ultizen.farm.model.proxy
{
	//import com.adobe.crypto.MD5;
	import com.ultizen.farm.core.ApplicationConfig;
	import com.volcano.mvc.model.IReqData;
	
	import flash.events.EventDispatcher;
	import flash.events.NetStatusEvent;
	import flash.events.TimerEvent;
	import flash.net.NetConnection;
	import flash.net.Responder;
	import flash.utils.Dictionary;
	import flash.utils.Timer;

	public class Connection extends EventDispatcher
	{
		private const URL:String =  ApplicationConfig.instance.baseSwfPath;
		public function Connection()
		{
			super();
			netConn= new NetConnection();
			netConn.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
			netConn.connect(URL);
			myTimer = new Timer(50, 0);
			myTimer.addEventListener(TimerEvent.TIMER, timerHandler);
		}
		private var netConn:NetConnection;
		private var que:Array = [];
        private var myTimer:Timer;
        
		private static var _instance:LoaderManager
	    public static function get instance():Connection
	    {
	        return _instance ||= new Connection;
	    }
		public function call(commond:String, data:IReqData):void
		{
			var dict:Dictionary = new Dictionary(true);
			dict["commond"] = commond;
			dict["data"] = data;
			que.push(dict);
			timerStart()
		}
		public function disconnect():void
		{
			netConn.close();
		}
		private function timerStart():void
		{
			if (que.length == 1)
			{
				myTimer.start();
			}
		}
        private function timerHandler(e:TimerEvent):void
        {
        	var dict:Dictionary = que[0];
        	var responder:Responder = new Responder(onGetResultSuccess, onGetResultFault);
            netConn.call(dict["commond"], responder, dict["data"]);
            que.splice(0, 1);
            if (que.length <= 0) myTimer.stop();
        }
        private function netStatusHandler(event:NetStatusEvent):void {
            switch (event.info.code) {
                case "NetConnection.Connect.Success": 
                    break;
                case "NetConnection.Connect.Failed":
                break;
                case "NetConnection.Connect.Closed":
                break;
                case "NetConnection.Call.Failed":
                	dispatchEvent(new NetConnectionEvent(NetConnectionEvent.CONNECT_FAILED));
                break;
            }
        }
        private function onGetResultSuccess(event:Object):void
        {
        	
        }
	    private function onGetResultFault(event:Object):void
	    {
	    	throw new Error("server api error: "+ "faultDetail= " + event["faultDetail"]+ " | faultString= " + event["faultString"]);
	    }

	}
}